package von.seiji.cn;

import von.seiji.cn.asset.Algorithm;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;


public abstract class AESUtil {

    public static SecretKey genSecretKey(Algorithm algorithm) {
        KeyGenerator keyGen = null;
        SecureRandom secureRandom = null;
        try {
            keyGen = KeyGenerator.getInstance(algorithm.value());
            secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes("utf-8"));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        }
        keyGen.init(256, secureRandom);
        return keyGen.generateKey();
    }

    public static String genSecretKeyStr(Algorithm algorithm) {
        SecretKey secretKey = genSecretKey(algorithm);
        byte[] encoded = secretKey.getEncoded();
        return Base64.getEncoder().encodeToString(encoded);
    }

    public static SecretKey strKey2SecretKey(String strKey,Algorithm algorithm) {
        byte[] bytes = Base64.getDecoder().decode(strKey);
        SecretKeySpec secretKey = new SecretKeySpec(bytes, algorithm.value());
        return secretKey;
    }

    public static byte[] encrypt(String content, SecretKey secretKey) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return cipher.doFinal(content.getBytes());
        } catch (Exception e) {
        }
        return null;
    }

    public static String decrypt(byte[] content, SecretKey secretKey) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(content);
            return new String(bytes);
        } catch (Exception e) {
        }
        return null;
    }
}